package com.taiji.dicom4cloud.smart.utils;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @ClassName FFmpegUtils
 * @Description
 * @Author HX
 * @Date 2021/9/27 10:13
 **/
@Slf4j
public class FFmpegUtils {


    //ffmpeg -i 01.00.00-01.00.13[M][0@0][0].mp4 -y -f  image2  -ss 10 -vframes 1  test1.jpg

    /**
     * 视频截图第一帧
     */
    public static void videoScreenShot(String inPath,String outPath) throws IOException {
        List<String> command = Lists.newArrayList();
        command.add("ffmpeg");
        command.add("-i");
        command.add(inPath);
        command.add("-ss");
        command.add("1");
        command.add("-f");
        command.add("image2");
        command.add(outPath);
        // 执行操作
        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
        InputStream errorStream = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            log.info(line);
        }
        if (br != null) {
            br.close();
        }
        if (isr != null) {
            isr.close();
        }
        if (errorStream != null) {
            errorStream.close();
        }
    }


    /**
     * 视频转码
     * @throws IOException
     */
    public static void videoConvert(String inPath,String outPath) throws IOException {
        // 构建命令
        List<String> command = Lists.newArrayList();
        command.add("ffmpeg");
        command.add("-i");
        command.add(inPath);
        command.add(outPath);
        // 执行操作
        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
        InputStream errorStream = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(errorStream);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            log.info(line);
        }
        if (br != null) {
            br.close();
        }
        if (isr != null) {
            isr.close();
        }
        if (errorStream != null) {
            errorStream.close();
        }
    }

    public static void main(String[] args) {

        try {
            FFmpegUtils.videoConvert("","");
        } catch (IOException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
    }
}
